import store from '../store';
import Web3 from 'web3';
import {Dialog} from "vant";
import func from "@/utils/funcUtil/base";
import Vue from "vue";
import i18n from "../plugin/lang/i18n";

const logStyle = {
    info: "background:#35495e ; padding: 1px; border-radius: 3px 0 0 3px; margin:5px 0; color: #fff",
    success: "background:#328ee6 ; padding: 1px; border-radius: 3px 0 0 3px; margin:5px 0; color: #fff"
};

const logMessage = (label, status) => {
    console.log(`%c ${label} %c ${status} `, logStyle.info, logStyle.success);
};


const metaMask = {
    // 初始化并获取账号
    async init() {
        return new Promise((resolve, reject) => {
            if (typeof window.ethereum === 'undefined') {
                reject(new Error('Consider installing MetaMask!'));
            } else {
                window.ethereum.request({method: 'eth_requestAccounts'})
                    .catch(reason => {
                        console.log(reason);
                        store.commit("SET_WALLET_CONNECT", false);
                        if (reason === 'User rejected provider access') {
                            reject(new Error('用户不想登录，你看该怎么办'));
                        } else {
                            reject(new Error('说明发生了意外'));
                        }
                    })
                    .then(async accounts => {
                        // 一旦获取了用户账号，你就可以签名交易
                        if (process.env.VUE_APP_OPEN_SIGN === 'true') {
                            try {
                                // 签名授权
                                const signature = await handleSignature(accounts);
                                store.commit("SET_WALLET_SIGN", signature);
                            } catch (error) {
                                // 用户拒绝签名
                                reject(error);
                                return;
                            }
                        } else {
                            logMessage('签名授权','关闭')
                        }
                        // 监听事件
                        initializeEvent();
                        store.commit("SET_WALLET_CONNECT", true);
                        store.commit("SET_WALLET_ACCOUNT", accounts[0]);
                        resolve(accounts);
                    });
            }
        });
    },
    // 初始化web3
    async initWeb3() {
        await this.init();
        return getWeb3();
    },

    initContract,
    getWeb3,
    getNetworkVersion,
    getChainId,
    getAccounts
};
// 监听事件
function initializeEvent() {
    window.ethereum.on('accountsChanged', (accounts) => {
        console.log(accounts);
        store.commit("SET_WALLET_ACCOUNT", accounts[0]);
        window.location.reload();
    });

    window.ethereum.on('chainChanged', (chainId) => {
        console.log(chainId);
        store.commit("SET_WALLET_CHAIN_ID", chainId);
        window.location.reload();
    });

    window.ethereum.on('message', (message) => {
        console.log(message);
    });
}
// 签名授权
async function handleSignature(accounts) {
    return new Promise((resolve, reject) => {
        const web3 = new Web3(window.ethereum);
        const message = func.getGuid();
        web3.eth.personal.sign(message, accounts[0], async (err, res) => {
            if (res != null && res !== undefined && res !== '') {
                logMessage('签名授权','通过')

                 try {
                    const {result} = await Vue.prototype.$encPost({
                        module: "Account", interface: "5000", data: {
                            message: message, signature: res, address: accounts[0],
                        }
                    });
                    if (result) {
                        store.commit("UPDATE_PAGE_STATUS", true);
                        resolve(res);
                    } else {
                        Dialog.alert({
                            title: i18n.t('m.提示'), message: i18n.t('m.签名授权失败，请重新授权！'),
                        }).then(() => {
                            window.location.reload();
                        });
                        reject(new Error('签名授权失败'));
                    }
                } catch (e) {
                    console.log(e);
                    console.log("check sign error");
                    reject(e);
                }
            } else {
                reject(new Error('签名失败'));
            }
        });
    });
}
// 初始化合约
function initContract(web3, abis) {
    return new Promise((resolve, reject) => {
        try {
            this.init().then(() => {
                // const web3 = getWeb3();
                if (web3 && abis) {
                    Object.keys(abis).forEach(key => {
                        const contract = new web3.eth.Contract(abis[key].abi, abis[key].address, {
                            from: store.state.wallet.account, value: 0, gas: 600000, gaslimit: 10
                        });
                        store.commit('SET_WALLET_CONTRACT', {key: key, contract: contract});
                    });
                }
                resolve();
            }).catch(error => {
                reject(error);
            });
        } catch (error) {
            reject(error);
        }
    });
}
// 获取web3
function getWeb3() {
    if (window.ethereum) {
        const web3 = new Web3(window.ethereum);
        store.commit('SET_WALLET_WEB3', web3);
        return web3;
    }
    return null;
}
// 获取网络版本
function getNetworkVersion() {
    if (!window.ethereum) return undefined;
    return window.ethereum.request({method: 'net_version'});
}
// 获取链ID
function getChainId() {
    if (!window.ethereum) return undefined;
    return window.ethereum.request({method: 'eth_chainId'});
}
// 获取账户
function getAccounts() {
    if (!window.ethereum) return undefined;
    return window.ethereum.request({method: 'eth_accounts'});
}
// 安装插件
export default function install(Vue) {
    if (install.installed) {
        return;
    }
    install.installed = true;
    Object.defineProperty(Vue.prototype, '$metaMask', {
        get() {
            return metaMask;
        }
    });
}
